package com.zengqingfa.juc.demo1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @fileName: SaleTicketTest
 * @author: zengqf3
 * @date: 2020-10-8 10:00
 * @description:
 */
public class SaleTicketTest2 {
    public static void main(String[] args) {

        Ticket2 ticket = new Ticket2();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}


class Ticket2 {

    private int ticketNum = 30;

    //非公平锁：可以插队，默认
    //公平锁：先来后到
    Lock lock = new ReentrantLock();

    public void sale() {
        //加锁
        lock.lock();
        try {
            if (ticketNum > 0) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (ticketNum--) + "张票,剩余" + ticketNum + "票");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }

    }
}

